package com.yixueyun.base.exception;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import java.util.ArrayList;

@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {
    //自定义异常
    @ResponseBody
    @ExceptionHandler(YiXueYunPlusException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public RestErrorResponse customException(YiXueYunPlusException e) {
        //记录自定义异常
        log.error("【系统异常】{}",e.getErrMessage(),e);

        return new RestErrorResponse(e.getErrMessage());

    }
    //系统异常
    @ResponseBody
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public RestErrorResponse exception(Exception e) {

        log.error("【系统异常】{}",e.getMessage(),e);
        if(e.getMessage().equals("不允许访问")) {
            return new RestErrorResponse("您没有权限使用此功能");
        }
        return new RestErrorResponse(CommonError.UNKOWN_ERROR.getErrMessage());
    }
    //JSR303异常
    @ResponseBody
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public RestErrorResponse methodArgumentNotValidException(MethodArgumentNotValidException e) {
        //错误信息集合
        ArrayList<String> error = new ArrayList<>();
        //拿到错误信息
        BindingResult bindingResult = e.getBindingResult();
        bindingResult.getFieldErrors().stream().forEach(item->{
            error.add(item.getDefaultMessage());
        });
        //将list错误信息拼接
        String errMessage = StringUtils.join(error, ",");
        log.error("【JSR303异常】{}",e.getMessage(),errMessage);

        return new RestErrorResponse(errMessage);
    }
}
